﻿/*****************************************************
 * 本类库的核心系 JNTemplate
 * (C) JNTemplate 2011
 * 作者：翅膀的初衷 QQ:4585839
 * 网址：http://www.JiNianNet.com
 *****************************************************/
using System;
using System.Text;
using System.Collections.Generic;
using JinianNet.JNTemplate.Process;
using System.Text.RegularExpressions;
using JinianNet.JNTemplate.Process.Element;
using JinianNet.JNTemplate.Process.Common;
using System.IO;

namespace JinianNet.JNTemplate
{
    public class Template : ITemplate
    {
        private TemplateContext _context;
        public TemplateContext Context
        {
            get
            {
                if (_context == null)
                {
                    _context = new TemplateContext();
                }
                return _context;
            }
            set { _context = value; }
        }

        private string _text;
        public string TemplateContent
        {
            get { return _text; }
            set { _text = value; }
        }

        public virtual void Render(TextWriter writer)
        {
            if (!string.IsNullOrEmpty(TemplateContent))
            {
                List<Token> element = new TemplateParser().ParserAll(new TemplateLexer(TemplateContent).FindAll());
                foreach (Token token in element)
                {
                    Token value;
                    if (token.TokenKind == TokenKind.Load)
                    {
                        LoadTag tag = token as LoadTag;
                        tag.BasePath = Context.CurrentPath;
                        value=tag;
                    }
                    else
                    {
                        value=token;
                    }
                    value.Parser(Context.TempData, writer);
                }
            }
        }

        public string Render()
        {
            string document;

            using (StringWriter writer = new StringWriter())
            {
                Render(writer);
                document = writer.ToString();
            }

            return document;
        }


        public void Set(string key, object value)
        {
            Context.TempData[key] = value;
        }

        public void Set(Dictionary<string, object> values)
        {
            foreach (KeyValuePair<string,object> value in values)
            {
                Set(value.Key, value.Value);
            }
        }

    }
}
